package io.jpress.commons.word;

import com.jfinal.kit.LogKit;
import io.jpress.JPressOptions;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.document.DocumentFamily;
import org.jodconverter.core.document.DocumentFormat;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.local.JodConverter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;

public class LibreOfficeUtil {

    //图片以 base64 方式导出
    private static final DocumentFormat HTML_EMBED_IMAGES =
            DocumentFormat.builder()
                    .from(DefaultDocumentFormatRegistry.HTML)
                    .storeProperty(DocumentFamily.TEXT, "FilterOptions", "EmbedImages")
                    .build();


    public static String parse(File wordFile) {

        String officeHome = JPressOptions.get("article_word_import_libreoffice_path");

        if (!LibreOfficeManager.me().initIfNecessary(officeHome)) {
            LogKit.error("WordManager is not started. Can not parse word!");
            return null;
        }

        //如果导出的文件存在
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        //word 转换为 html
        if (!convertWordToStream(wordFile, outStream)) {
            return null;
        }

        return DocumentUtil.process(outStream.toString(), new String[]{"body", "p", "span"});
    }


    private static boolean convertWordToStream(File wordFile, OutputStream stream) {
        try {
            JodConverter.convert(wordFile)
                    .to(stream)
                    .as(HTML_EMBED_IMAGES)
                    .execute();
            return true;
        } catch (OfficeException e) {
            LogKit.error(e.toString(), e);
        }
        return false;
    }


    public static void main(String[] args) {
        JPressOptions.set("article_word_import_libreoffice_path", "/Applications/LibreOffice.app/Contents");
        String Str = LibreOfficeUtil.parse(new File("/Users/michael/Desktop/项目/test.doc"));
        System.out.println(Str);
    }
}
